package leetcode.DFS_BFS;

/**
 * @author mazouri
 * @create 2021-09-22 19:34
 */
public class _200_numIslands {
    int count = 0;
    char[][] grid;

    public int numIslands(char[][] grid) {
        this.grid = grid;

        for (int x = 0; x < grid.length; x++) {
            for (int y = 0; y < grid[0].length; y++) {
                if (grid[x][y] == '1') {
                    dfs(x, y);
                    count++;
                }
            }
        }
        return count;
    }

    private void dfs(int x, int y) {
        if (isValid(x, y)) {
            grid[x][y] = '0';

            dfs(x + 1, y);
            dfs(x, y + 1);
            dfs(x - 1, y);
            dfs(x, y - 1);
        }
    }

    private boolean isValid(int x, int y) {
        if (x >= grid.length || x < 0 || y >= grid[0].length || y < 0) return false;
        return grid[x][y] != '0';
    }
}
